package video.dali.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import video.dali.common.Result;
import video.dali.common.config.JwtProperties;
import video.dali.common.dto.UserDto;
import video.dali.common.dto.UserLoginDto;
import video.dali.common.entity.User;
import video.dali.common.utils.JwtUtil;
import video.dali.common.utils.SaltMD5Util;
import video.dali.common.vo.UserLoginVO;
import video.dali.common.vo.UserVo;
import video.dali.service.UserService;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;


    @GetMapping("/hello")
    public String hello(){
        return "hello,你成功创建了";
    }

    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDto userLoginDto){
        log.info("用户登录,username:{}", userLoginDto.getUsername());
        User user = userService.login(userLoginDto);
        if (Objects.isNull(user)){
            return Result.error("密码不正确或用户名已被使用");
        }
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String jwt = JwtUtil.createJwt(claims, jwtProperties.getSecretKey(), jwtProperties.getTtl());
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        userLoginVO.setToken(jwt);
        userLoginVO.setId(user.getId());
        return Result.success(userLoginVO);


    }


    /**
     * 删除用户
     * @param username
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestParam String username){
        log.info("删除用户，username:{}", username);
        userService.deleteByUsername(username);
        return Result.success();
    }


    /**
     * 根据姓名查询用户
     * @param username
     * @return
     */
    @GetMapping("/list")
    public Result<UserVo> list(@RequestParam String username){
        log.info("根据姓名查询用户,username:{}",username);
        User user = userService.list(username);
        log.info(user.toString());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return Result.success(userVo);
    }


    /**
     * 更新用户信息
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody UserDto userDto){
        log.info("更新用户信息,userDto:{}", userDto.toString());
        userService.update(userDto);
        return Result.success();
    }




}
